<?php

namespace Forms;

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Identical;
use Models\Doctypes;
use Phalcon\Mvc\Model\Message as ModelMessage;
use Phalcon\Validation\Message;
use Phalcon\Validation\Message\Group;

class TopicForm extends Form {

    public function initialize($entity = null, $options = null) {
        $name = new Text('name');
        $name->addValidators(array(
            new PresenceOf(array(
                'message' => 'The name is required'
                    ))
        ));

        $this->add($name);

        $doctype = new Select('doctype', Doctypes::find(), array(
            'using' => array('id', 'name'),
            'useEmpty' => true,
            'emptyText' => 'Chọn loại tài liệu',
            'emptyValue' => '',
        ));
        $doctype->addValidators(array(
            new PresenceOf(array(
                'message' => 'The document type is required'
                    ))
        ));
        $this->add($doctype);


        // CSRF
        $csrf = new Hidden('csrf');

        $csrf->addValidator(new Identical(array(
            'value' => $this->security->getSessionToken(),
            'message' => 'CSRF validation failed'
        )));

        $this->add($csrf);
    }

    /**
     * Prints messages for a specific element
     */
    public function messages($name) {
        if ($this->hasMessagesFor($name)) {
            foreach ($this->getMessagesFor($name) as $message) {
                $this->flash->error($message);
            }
        }
    }
    
     public function appendMessage($message, $field, $type = null) {
        if (is_string($message)) {
            $message = new Message($message, $field, $type);
        }

        if ($message instanceof Message || $message instanceof ModelMessage) {
            // Check if there is a group for the field already.
            if (!is_null($this->_messages) && array_key_exists($field, $this->_messages)) {
                $this->_messages[$field]->appendMessage($message);
            } else {
                $this->_messages[$field] = new Group(array($message));
            }
        } else {
            throw new Exception("Can't append message into the form, invalid type.");
        }
    }

}
